import React, { PureComponent } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import { Table, Button, Card, Modal, Form, Icon, Input, Menu, Dropdown, message, TreeSelect, Select, Switch, Row,TimePicker , Col,DatePicker,Upload } from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import StandardTable from '../../components/StandardTable';
import styles from '../Mana/Role.less';
import ReactDOM from 'react-dom';
// 引入编辑器以及编辑器样式
import BraftEditor from 'braft-editor'
import 'braft-editor/dist/braft.css';

//课程管理 -admin 单独
const RangePicker = DatePicker.RangePicker;
const Option = Select.Option;
const FormItem = Form.Item;
const { TextArea } = Input;
var school_select=[];//学校
var course_select=[];//父级课程
var disableds=true;//默认禁用
var ages=[];//起止年龄


//默认状态
var state;
//时间戳 转化为时间格式
var Y,M,D,h,m,s="";
function timestampToTime(timestamp){
    var date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000   //* 1000
    Y = date.getFullYear() + '-';
    M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
    D = date.getDate() + ' ';
    h = date.getHours() + ':';
    m = date.getMinutes() + '-';
    s = date.getSeconds();
    return m+s;
}

//选择类型 a.b.c，父级是否可选择
function courseTypeChange(value){
	if(value==2){
		disableds=false;
	}else{
		disableds=true;
	}
}
//起止年龄
function agesOnChange(value){
	ages=value.split(",");
}


//图片
var headerimg="";
var imageUrl="";
var hidden;
//图片
function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}

//图片封面
class Avatar extends React.Component {
  state = { loading: false, };
  handleChange = (info) => {
    if (info.file.status === 'uploading') {
      this.setState({ loading: true });
      return;
    }
    if(info.file.status === 'done') {
    	headerimg=info.file.response.obj.path;
    	imageUrl=info.file.response.obj.path;
	    getBase64(info.file.originFileObj, imageUrl => this.setState({
	        imageUrl,
	        loading: false,
	    }));
    }
  }

  render() {
    const uploadButton = (
      <div>
        <Icon type={this.state.loading ? 'loading' : 'plus'} />
        <div className="ant-upload-text">Upload</div>
      </div>
    );
	if(imageUrl==undefined){
	  	 imageUrl = this.state.imageUrl;
	}else{
	  	headerimg=imageUrl;
	}
	
    const urls="api/web/attachment/upload.manage?token="+sessionStorage.getItem('token');
    return (
      <Upload
        name="file"
        style={{width:'200px'}}
        listType="picture-card"
        className="avatar-uploader"
        showUploadList={false}
        action={urls}
        method="POST"
        enctype="multipart/form-data"
        onChange={this.handleChange}
      >
        {imageUrl ? <img src={imageUrl} alt=""  style={{width:'200px'}} /> : uploadButton}
      </Upload>
    );
  }
}

/*描述内容-按钮 -点击弹出富文本框*/
class AvatarButton extends React.Component {
  state = { visible: false }
  showModal = () => {
    this.setState({
      visible: true,
    });
  }
  handleOk = (e) => {
    console.log(e);
    this.setState({
      visible: false,
    });
  }
  handleCancel = (e) => {
    console.log(e);
    this.setState({
      visible: false,
    });
  }
  render() {
    return (
      <div>
        <Button type="primary" onClick={this.showModal}>编辑内容</Button>
        <Modal
          maskClosable={false}
      	  destroyOnClose={true}
          title="描述内容"
          width="90%"
          visible={this.state.visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
        >
         <Demo/>
        </Modal>
      </div>
    );
  }
}


var contents="";//富文本框
class Demo extends React.Component {
  render () {
    const editorProps = {
      height: 500,
      contentFormat: 'html',
      initialContent: contents,
      onChange: this.handleChange,
      media:{
			  allowPasteImage: true, // 是否允许直接粘贴剪贴板图片（例如QQ截图等）到编辑器
			  image: true, // 开启图片插入功能
			  video: false, // 开启视频插入功能
			  audio: false, // 开启音频插入功能
			  validateFn: null, // 指定本地校验函数，说明见下文
			  uploadFn: this.uploadFns, // 指定上传函数，说明见下文
			  removeConfirmFn: null, // 指定删除前的确认函数，说明见下文
			  onRemove: null, // 指定媒体库文件被删除时的回调，参数为被删除的媒体文件列表(数组)
			  onChange: null, // 指定媒体库文件列表发生变化时的回调，参数为媒体库文件列表(数组)
			  onInsert: null, // 指定从媒体库插入文件到编辑器时的回调，参数为被插入的媒体文件列表(数组)
			},
    }
    return (
      <div className="demo">
        <BraftEditor {...editorProps}/>
      </div>
    )
  }
  handleChange = (content) => {
    contents=content;
  }
  uploadFns = (param) => {
	  const serverURL = "api/web/attachment/upload.manage?token="+sessionStorage.getItem('token');
	  const xhr = new XMLHttpRequest
	  const fd = new FormData();
	  // libraryId可用于通过mediaLibrary示例来操作对应的媒体内容
	  const successFn = (response) => {
	    // 假设服务端直接返回文件上传后的地址
	    // 上传成功后调用param.success并传入上传后的文件地址
	    param.success({
	      url: JSON.parse(xhr.response).obj.path
	    });
	  }
	  const progressFn = (event) => {
	    // 上传进度发生变化时调用param.progress
	    param.progress(event.loaded / event.total * 100)
	  }
	  const errorFn = (response) => {
	    // 上传发生错误时调用param.error
	    param.error({
	      msg: 'unable to upload.'
	    })
	  }
	  xhr.upload.addEventListener("progress", progressFn, false)
	  xhr.addEventListener("load", successFn, false)
	  xhr.addEventListener("error", errorFn, false)
	  xhr.addEventListener("abort", errorFn, false)
	  fd.append('file', param.file)
	  xhr.open('POST', serverURL, true)
	  xhr.send(fd)
	}
}


/*表单弹出层*/
const CreateForm = Form.create()(props => {
  const { modalVisible, form, handleAdd, handleModalVisible,title,obj} = props;
  const {getFieldDecorator} = form;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
            if(fieldsValue.nickName==undefined)  fieldsValue.nickName="";//昵称
	     	if(fieldsValue.parentId == undefined)	 fieldsValue.parentId=""; //机构
			if(fieldsValue.state == undefined)	 fieldsValue.state="1"; //状态
			if(fieldsValue.courseType == undefined) fieldsValue.courseType="2";//课程类型
			if(fieldsValue.hotState == undefined) fieldsValue.hotState="0"; //热门
			if(fieldsValue.newState == undefined) fieldsValue.newState="0"; //最新
			if(fieldsValue.remark == undefined) fieldsValue.remark="";//备注
			if(fieldsValue.discountPrice == undefined) fieldsValue.discountPrice="";//折扣价
			if(fieldsValue.period==undefined)  fieldsValue.period="";//学习分钟数
			if(fieldsValue.state == undefined) { 	fieldsValue.state = 1}
			fieldsValue.coverPicture=headerimg;
			var ages=timestampToTime(fieldsValue.fitAge);
			console.log(ages);
			if(ages!=undefined){
				var arr=ages.split("-");
				fieldsValue.fitAge=arr[0];
	  			fieldsValue.endAge=arr[1];
			}else{
  				fieldsValue.fitAge="";
  				fieldsValue.endAge="";
			}
			fieldsValue.description=contents.replace(/\#/g, '$aoxin');//描述
	      	form.resetFields();
	     	handleAdd(title,obj.courseId,fieldsValue);
    });
  };
  return (
    <Modal
      maskClosable={false}
      destroyOnClose={true}
      width={'60%'}
      title={title}
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible(false,'','')}
    >
    	<Form layout="horizontal">
          	<FormItem label="课程名称" labelCol={{span: 8}}  wrapperCol={{span: 12}} className={styles.w50left}>
	            {getFieldDecorator('name', {
	            	initialValue:obj.name,
	              	rules: [{ required: true, message: '课程名称不能为空!' }],
	            })(<Input  placeholder="请输入课程名称"  /> )}
          	</FormItem>
          	<FormItem label="简称" labelCol={{span: 8}}  wrapperCol={{span: 12}} className={styles.w50left}>
	            {getFieldDecorator('nickName', {
	            	initialValue:obj.nickName,
	            })(<Input placeholder="请输入课程简称" />)}
          	</FormItem>

          	<FormItem label="状态" labelCol={{span: 8}}  wrapperCol={{span: 12}} className={styles.w50left}>
            	{getFieldDecorator('state', {
            		initialValue:obj.state==undefined ? "1":obj.state,
            	})(<Select placeholder="请选择状态">
             			<Option value="1">有效</Option>
			            <Option value="0">无效</Option>
			        </Select>)}
          	</FormItem>

          	<FormItem label="学习分钟数" labelCol={{span: 8}}  wrapperCol={{span: 12}} className={styles.w50left}>
            	{getFieldDecorator('period', {
            		initialValue:obj.period,
            	})(<Input disabled placeholder="请输入学习分钟数" />)}
          	</FormItem>
          	<FormItem label="起止年龄" labelCol={{span: 8}}  wrapperCol={{span: 12}} className={styles.w50left}>
            	{getFieldDecorator('fitAge', {
            		initialValue:obj.fitAge==undefined ? moment('3-6','mm-ss'): moment(obj.fitAge,'mm-ss') ,//obj.fitAge,moment('08-23','mm-ss')
            		rules: [{ required: true, message: '起止年龄不能为空!' }],
            	})(<TimePicker  format={"mm-ss"} allowEmpty inputReadOnly placeholder="请选择起止年龄" style={{width:'100%'}}/>
			       )}
          	</FormItem>
          	<FormItem label="原价" labelCol={{span: 8}}  wrapperCol={{span: 12}}  className={styles.w50left}>
            	{getFieldDecorator('price', {
            		initialValue:obj.price,
            		rules: [{ required: true, message: '原价不能为空!' }],
            	})(<Input placeholder="请输入原价"/>)}
          	</FormItem>
          	<FormItem label="实际价格" labelCol={{span: 8}}  wrapperCol={{span: 12}}  className={styles.w50left}>
            	{getFieldDecorator('discountPrice', {
            		initialValue:obj.discountPrice,
            		rules: [{ required: true, message: '实际价格不能为空!' }],
            	})(<Input placeholder="请输入实际价格"/>)}
          	</FormItem>
          	<FormItem label="是否可见" labelCol={{span: 8}}  wrapperCol={{span: 12}} className={styles.w50left}>
            	{getFieldDecorator('isVisible', {
            		initialValue:obj.isVisible==undefined ? "Y":obj.isVisible,
            		rules: [{ required: true, message: '是否可见必选!' }],
            	})(<Select placeholder="请选择是否最新">
             			<Option value="Y">可见</Option>
			            <Option value="N">不可见</Option>
			        </Select>)}
          	</FormItem>
          	<FormItem label="是否热门" labelCol={{span: 8}}  wrapperCol={{span: 12}} className={styles.w50left}>
            	{getFieldDecorator('hotState', {
            		initialValue:obj.hotState==undefined ? "0":obj.hotState,
            	})(<Select placeholder="请选择是否热门">
             			<Option value="1">是</Option>
			            <Option value="0">否</Option>
			        </Select>)}
          	</FormItem>
          	<FormItem label="是否最新" labelCol={{span: 8}}  wrapperCol={{span: 12}} className={styles.w50left}>
            	{getFieldDecorator('newState', {
            		initialValue:obj.newState==undefined ? "1":obj.newState,
            	})(<Select placeholder="请选择是否最新">
             			<Option value="1">是</Option>
			            <Option value="0">否</Option>
			        </Select>)}
          	</FormItem>
          	 <FormItem label="简介"  labelCol={{span: 4}}  wrapperCol={{span: 18}}>
	            {getFieldDecorator('briefIntroduction', {
	            	initialValue:obj.briefIntroduction,
	            	rules: [{ required: true, message: '简介不能为空!' }],
	            })(
	              	<TextArea></TextArea>
	            )}
	        </FormItem>
          	<FormItem label="备注" labelCol={{span: 4}}  wrapperCol={{span: 12}}>
            	{getFieldDecorator('remark', {
            		initialValue:obj.remark,
            	})(<Input placeholder="请输入备注"/>)}
          	</FormItem>
          	<FormItem label="封面图片" labelCol={{span: 4}}  wrapperCol={{span: 18}}>
	           {(<Avatar />)}
	        </FormItem>
          	<FormItem label="描述" labelCol={{span: 4}}  wrapperCol={{span: 18}}>
	           {getFieldDecorator('description', {
	            	initialValue:obj.description,
	            })(<AvatarButton />)}
          	</FormItem>
    	</Form>
    </Modal>
  );
});


@connect(({ campucourse, loading ,menu }) => ({
  campucourse,
  loading: loading.models.campucourse,
  threeMenu: menu.threeMenu,
}))
@Form.create()
export default class TableList extends PureComponent {
	state = {
	    modalVisible: false,
	    selectedRows: [],
	    formValues: {},
	    obj: "",
	};
    componentDidMount() {
		/*按钮查询*/
		this.props.dispatch({
			type: 'menu/fetch_three_menu',
		});
		//默认查询table 数据
		this.props.dispatch({
			type: 'campucourse/fetch_course',
			payload: {
				state :1,
			},
		});
		//默认查询 父级课程 select
		this.props.dispatch({
			type: 'campucourse/fetch_courseselect',
			callback: (res,data) => {
				course_select=[];
				for (let i = 0; i < data.length; i++) {
				  course_select.push(<Option key={data[i].courseId}>{data[i].name}</Option>);
				}
			}
		});
		//默认查询 学校 select
		this.props.dispatch({
			type: 'campucourse/fetch_ListByschoolselect',
			callback: (res,data) => {
				school_select=[];
				for (let i = 0; i < data.length; i++) {
				  school_select.push(<Option key={data[i].id}>{data[i].value}</Option>);
				}
			}
		});
	}
    //分页查询
	handleStandardTableChange = (pagination, filtersArg, sorter) => {
	    const { dispatch } = this.props;
	    const { formValues } = this.state;
	    const filters = Object.keys(filtersArg).reduce((obj, key) => {
	    const newObj = { ...obj };
	      newObj[key] = getValue(filtersArg[key]);
	      return newObj;
	    }, {});
	    const params = {
	      currentPage: pagination.current,
	      pageSize: pagination.pageSize,
	      ...formValues,
	      ...filters,
	    };
	    if (sorter.field) {
	      params.sorter = `${sorter.field}_${sorter.order}`;
	    }
	    dispatch({
	      type: 'campucourse/fetch_course',
	      payload: params,
	    });
	};
	handleSelectRows = rows => {
	    this.setState({
	      selectedRows: rows,
	    });
	};
	/*重置*/
	handleFormReset = () => {
		const {	form,	dispatch} = this.props;
		form.resetFields();
		this.setState({	formValues: {},});
		dispatch({type: 'campucourse/fetch_course',});
	}
	/*查询*/
	handleSearch = e => {
	    e.preventDefault();
	    const { dispatch, form } = this.props;
	    form.validateFields((err, fieldsValue) => {
		    if (err) return;
		    const values = {  ...fieldsValue,};
		    this.setState({ formValues: values,});
			if(values.name==undefined){	values.name=""}
			if(values.courseType==undefined){	values.courseType="2"}
			if(values.newState==undefined){	values.newState=""}
			if(values.hotState==undefined){	values.hotState=""}
			if(values.state==undefined){	values.state=""}
	        dispatch({
		        type: 'campucourse/fetch_course',
		        payload:{...values},
	        });
	    });
	};
	/*弹窗*/
    handleModalVisible = (flag,record,title) => {
  	    const { selectedRows } = this.state;
  	    contents="";
  	    imageUrl="";
	  	if(flag==false){
	  		this.setState({
		      modalVisible: false,
		    });
	  	}else{
	  		var obj={};
	  		if(title=="新建"){
		  		this.setState({
			      modalVisible: !!flag,
			      title: title,
			      obj: obj,
			    });
	  		}else{
		  		if(record==undefined||Object.keys(selectedRows).length==0){
			    	message.info("还未选择项");
			    }else if(Object.keys(selectedRows).length>1){
			    	message.info("只可选择一项");
			    }else{
			    	this.props.dispatch({
						type: 'campucourse/fetchId_course',
						payload: {courseId : selectedRows[0].courseId,},
						callback: (res,data) => {
							var data=data[0];
							if(res == 1) {
								/*if(data.schoolId!=Array){
									if(data.schoolId!=0&&data.schoolId!=undefined&&data.schoolId.length>1){
										data.schoolId=data.schoolId.split(",");
									}else if(data.schoolId==0){
										data.schoolId=undefined
									}
								}*/
								if(data.courseType!=undefined){//课程类型
									if(data.courseType==2){
										disableds=false;
									}else{
										disableds=true;
									}
									data.courseType+=''
								}
								if(data.state!=undefined){//状态
									data.state+=''
								}
								if(data.parentId!=undefined){//父级
									data.parentId+=''
								}
								if(data.hotState!=undefined){//是否热门
									data.hotState+=''
								}
								if(data.newState!=undefined){//是否最新
									data.newState+=''
								}
								data.isVisible +="";
								data.fitAge=data.fitAge+"-"+data.endAge;
								contents=data.description.replace(/\$aoxin/g, '#');;
								imageUrl=data.coverPicture;
								data.courseId=data.courseId;
								this.setState({
									modalVisible: true,
									title: title,
									obj: data,
								});
							}else{ //失败
								message.error(resMsg);
							}
						},
					});
			    }
		  	}
	  	}
  	};
	/*新增,修改*/
	handleAdd = (title,Id,fields) => {
		console.log(headerimg)
		var name = fields.name;
		var briefIntroduction = fields.briefIntroduction;
		if(headerimg == "" || headerimg == undefined)
		return;
		if(title=="新建"){
			this.props.dispatch({
		      type: 'campucourse/add_course',
		      payload: {...fields,},
		      callback: (res,resMsg) => {
		      	if(res==1){
		      		message.success(resMsg);
		      	}else{
		      		message.error(resMsg);
		      	}
		      },
		    });
	  	}else if(title=="编辑"){
	  		this.props.dispatch({
		      type: 'campucourse/edit_course',
		      payload: {
		      	...fields,
		      	courseId:Id,
		      },
		      callback: (res,resMsg) => {
		      	this.state.selectedRows=[];
		      	if(res==1){
		      		message.success(resMsg);
		      	}else{
		      		message.error(resMsg);
		      	}
		      },
		    });
	  	}
	    this.setState({
	      modalVisible: false,
	    });
	};
	/*删除 启用和禁用*/
	confirmModel = (title, Id) => {
		const {
			dispatch
		} = this.props;
		const {
			selectedRows
		} = this.state;
		if(Id == undefined && Object.keys(selectedRows).length == 0) {
			message.info("还未选择项");
		} else {
			var Ids = [];
			if(Id != undefined) {
				Ids = Id;
			} else if(selectedRows != null) {
				Ids.push(selectedRows.map(row => row.courseId).join(','));
			}
			if(title != "删除") {
				var state;
				if(title == "禁用") {
					state = 0;
				} else {
					state = 1;
				}
				dispatch({
					type: 'campucourse/disabled_course',
					payload: {
						courseIds: Ids,
						state :state,
					},
					callback: (res, resMsg) => {
						this.state.selectedRows=[];
						if(res == 1) {
							message.success(resMsg);
						} else {
							message.error(resMsg);
						}
					},
				});
				
			} else {
				Modal.confirm({
					title: '是否删除当前数据选中',
					content: '',
					onOk() {
						dispatch({
							type: 'campucourse/remove_classroom',
							payload: {
								courseIds: Ids,
							},
							callback: (res, resMsg) => {
								if(res == 1) {
									message.success(resMsg);
								} else {
									message.error(resMsg);
								}
							},
						});
					},
				});
			}
		}
	}
	renderSimpleForm() {
	    const { getFieldDecorator } = this.props.form;
	    return (
	        <Form onSubmit={this.handleSearch} layout="inline">
		        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
		           <Col md={8} sm={24}>
			            <FormItem label="课程名称">
			              	{getFieldDecorator('name')(
			                <Input placeholder="请输入" />
			              )}
			            </FormItem>
		          	</Col>
		          	 <Col md={8} sm={24}>
			            <FormItem label="是否最新">
				            {getFieldDecorator('newState')(
				                <Select placeholder="请选择" style={{ width: '100%' }}>
				                  <Option value="1">是</Option>
				                  <Option value="0">否</Option>
				                </Select>
				            )}
			            </FormItem>
		          	</Col>
		          	<Col md={8} sm={24}>
			            <FormItem label="是否热门">
			              	{getFieldDecorator('hotState')(
			                <Select placeholder="请选择" style={{ width: '100%' }}>
			                 	<Option value="1">是</Option>
		                  		<Option value="0">否</Option>
			                </Select>
			              	)}
			            </FormItem>
		          	</Col>
		        </Row>
		        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
			       <Col md={8} sm={24}>
			            <FormItem label="状态">
			              	{getFieldDecorator('state')(
			                <Select placeholder="请选择" style={{ width: '100%' }}>
			                 	<Option value="1">有效</Option>
		                  		<Option value="0">无效</Option>
			                </Select>
			              	)}
			            </FormItem>
		          	</Col>
		            <Col md={16} sm={24}>
			            <FormItem>
				            <span style={{ float: 'right', marginBottom: 24 }}>
				            <Button type="primary" htmlType="submit">查询</Button>
				            <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>重置</Button>
				            </span>
			            </FormItem>
		          	</Col>
		        </Row>
		    </Form>
	    );
	}
	render() {
	    const { campucourse: { data }, loading ,threeMenu} = this.props;
	    const { selectedRows, modalVisible,title,obj } = this.state;
	    const columns = [
			{
				title: '序号',
				dataIndex: 'courseId',
				key: 'courseId',
				render: (text, record, index) =>{return index+1}
			},{
				title: '课程名称',
				dataIndex: 'name',
				key: 'name',
			},{
				title: '原价',
				dataIndex: 'price',
				key: 'price',
			}, {
				title: '实际价格',
				dataIndex: 'discountPrice',
				key: 'discountPrice',
			},{
				title: '状态',
				dataIndex: 'state',
				key: 'state',
				render: (text, record, index) =>{
					if(record.state==1)	return "有效"
					else if(record.state==0)	return "无效"
				}
			}
		];
	    const parentMethods = {
	      	handleAdd: this.handleAdd,
	      	handleModalVisible: this.handleModalVisible,
	      	confirmModel:this.confirmModel,
	    };
	    return (
	    	<PageHeaderLayout title="课程系统/课程管理">
	      	<Card bordered={false}>
	          <div className={styles.tableList}>
	            <div className={styles.tableListForm}>{this.renderSimpleForm()}</div>
	            <span>
	            	<Button type="primary" onClick={() => this.handleModalVisible(true,'','新建')} style={{ marginLeft: 8 }}>新建</Button>
	            	<Button type="primary"  onClick={() => this.handleModalVisible(true,'','编辑')} style={{ marginLeft: 8 }}>编辑</Button>
				    <Button type="primary"  onClick={() => this.confirmModel('启用')} style={{ marginLeft: 8 }}>启用</Button>
				    <Button type="ghost"  onClick={() => this.confirmModel('禁用')} style={{ marginLeft: 8 }}>禁用</Button>
	            </span>
	            <StandardTable
	              selectedRows={selectedRows}
	              loading={loading}
	              data={data}
	              columns={columns}
	              onSelectRow={this.handleSelectRows}
	              onChange={this.handleStandardTableChange}
	            />
	          </div>
	        <CreateForm {...parentMethods} modalVisible={modalVisible} title={title} obj={obj}/>
	      </Card>
	       </PageHeaderLayout>
	    );
	}
}
